package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.fastdfs.FastDFSClient;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.MuMaterDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMateriaService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Log4j2
public class WmMateriaServiceImpl extends ServiceImpl<WmMaterialMapper , WmMaterial> implements WmMateriaService {
    @Autowired
    private FastDFSClient fastDFSClient;
    @Value("${fdfs.url}")
    private String fdfsServerUrl;

    /**
     * 上传图片
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        if(multipartFile == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"图片不存在");
        }
        String s = null;
        try {
             s = fastDFSClient.uploadFile(multipartFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //保存图片信息到数据库中
        WmUser user = WmThreadLocalUtils.getUser();

        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setType((short)0);
        wmMaterial.setUrl(s);
        wmMaterial.setUserId(user.getId());
        save(wmMaterial);
        wmMaterial.setUrl(fdfsServerUrl+s);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(MuMaterDto muMaterDto) {
        if (muMaterDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        muMaterDto.checkParam();
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        //获取当前登录的用户
        Integer uid = WmThreadLocalUtils.getUser().getId();
        wrapper.eq(WmMaterial::getUserId , uid);
        //判断是否有查询条件
        if(muMaterDto.getIsCollection() != null && muMaterDto.getIsCollection().shortValue() == 1 ){
            wrapper.eq(WmMaterial::getIsCollection , muMaterDto.getIsCollection());
        }
        //根据时间排序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        IPage page = new Page<>(muMaterDto.getPage() , muMaterDto.getSize());
        IPage page1 = page(page, wrapper);
        ResponseResult result = new PageResponseResult(muMaterDto.getPage() , muMaterDto.getSize() , (int)page1.getTotal());
        List<WmMaterial> list = page1.getRecords();
        list = list.stream().map(iterm->{
            iterm.setUrl(fdfsServerUrl+iterm.getUrl());
            return iterm;
        }).collect(Collectors.toList());
        result.setData(list);
        return result;
    }

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Override
    public ResponseResult delPicture(Integer id) {
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断当前图片是否被引用
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNewsMaterial::getMaterialId , id);
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);
        if(count > 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID , "图片被引用,不能删除");
        }
        String url = wmMaterial.getUrl().replace(fdfsServerUrl , "");
        try {
            fastDFSClient.delFile(url);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateStatus(Integer id, short type) {
        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer uid = WmThreadLocalUtils.getUser().getId();
        LambdaUpdateWrapper<WmMaterial> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(WmMaterial::getId , id)
                .eq(WmMaterial::getUserId , uid)
                .set(WmMaterial::getIsCollection , type);
        update(wrapper);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
